package com.yupi.yupicturebackend.manager.message;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class EmailManager {

    @Resource
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.nickname}")
    private String nickname;

    @Value("${spring.mail.username}")
    private String from;


    @Async(value="emailThreadPool")
    public void sendEmailCode(String to,String subject,String code){
        log.info("发送邮件验证码[{}]到[{}]",code,to);
        Map<String,Object> map= new HashMap<>();
        map.put("code",code);
        sendEmailCode(to,subject,map);


    }
    /**
     * 发送邮件
     * @param to
     * @param subject
     * @param contentMap
     */
    public void sendEmailCode(String to, String subject, Map<String,Object> contentMap){
        try{
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(nickname+"<"+from+">");
            helper.setTo(to);
            helper.setSubject(subject);
            // 设置邮件内容
            helper.setText(EmailUtils.emailContentTemplate("templates/EmailCodeTemplate.html", contentMap), true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送注册成功邮件
     * @param to
     * @param subject
     */
    public void sendRegisterSuccessEmail(String to, String subject,String userPassword){
        try{
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(nickname+"<"+from+">");
            helper.setTo(to);
            helper.setSubject(subject);
            // 邮件内容
            helper.setText(EmailUtils.emailContentTemplate("templates/EmailRegisterSuccessTemplate.html").replace("{{userPassword}}",userPassword), true);
            javaMailSender.send(message);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }




}
